package com.bobo.service.user;

import com.bobo.dao.favourite.FavouriteDaoImpl;
import com.bobo.dao.favourite.IFavouriteDao;
import com.bobo.dao.topic.ITopicDao;
import com.bobo.dao.topic.TopicDaoImpl;
import com.bobo.dao.user.IUserDao;
import com.bobo.dao.user.UserDaoImpl;
import com.bobo.dto.Page;
import com.bobo.model.Topic;
import com.bobo.model.User;
import com.bobo.util.MD5;

import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Created by bobo on 16-10-28.
 */
public class UserServiceImpl implements IUserService{
    IUserDao userDao = new UserDaoImpl();
    @Override
    public Integer create(User user) {
        String pwd = user.getPassword();
        try {
            pwd = MD5.md5(pwd);
            user.setPassword(pwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return userDao.create(user);
    }

    @Override
    public boolean upd(User user) {
        return userDao.upd(user);
    }

    @Override
    public boolean updPwd(User user) {
        String pwd = user.getPassword();
        try {
            pwd = MD5.md5(pwd);
            user.setPassword(pwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return userDao.updPwd(user);
    }

    @Override
    public boolean del(Integer id) {
        return userDao.delete(id);
    }

    @Override
    public User getUser(Integer id) {


        User user = null;
        user = userDao.getUser(id);

        return user;
    }

    @Override
    public Page<User> getUsers(Integer current, Integer pageSize, Integer status) {
        Page<User> page = new Page<>();
        page.setCurrent(current);
        page.setPageSize(pageSize);
        Integer count = userDao.getCount(status);
        float pagenum = count.floatValue()/pageSize.floatValue();
        page.setPageNum((int) Math.ceil(pagenum));
        page.setList(userDao.getUsers(current,pageSize,status));
        return page;
    }

    @Override
    public User updQuery(Integer id, String password) {
        String pwd = null;
        try {
            pwd = MD5.md5(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return userDao.updQuery(id,pwd);
    }

    @Override
    public User userCompare(String username, String password) {
        String pwd = null;
        User user = null;
        try {
            pwd = MD5.md5(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if(username!=null && !"".equals(username)){
            if(username.contains("@")){
                user = userDao.userCompare(null, username, pwd);
            }else {
                user = userDao.userCompare(username, null, pwd);
            }
        }
        return user;
    }
}
